

const babel = require('@babel/core')
const types = require('@babel/types')
const transformClasses = require('@babel/plugin-transform-classes')

const transformClasses2 = {
    visitor: {
        ClassDeclaration(path) {
            const { node } = path
            const { id, body } = node;
            const classMethods = body.body // [constructorNode, getNameNode]
            const newNodes = [];
            classMethods.forEach(classMethod => {
                if (classMethod.kind === 'constructor') { // 转为原函数
                    const constructor = types.functionDeclaration(id, classMethod.params, classMethod.body)
                    //  id===Person  分params为参数   body为函数体
                    newNodes.push(constructor)

                } else { // 转化为 原型方法
                    const AssignmentExpression = types.assignmentExpression(
                        '=', // 语法类型
                        types.memberExpression(  //  Person上的prototype属性
                            types.memberExpression(id, types.identifier('prototype')),
                            classMethod.key
                        ),
                        types.functionExpression( // 函数参数 函数体
                            null,
                            classMethod.params,
                            classMethod.body
                        )

                    )
                    newNodes.push(AssignmentExpression)
                }
            })
            if (newNodes.length === 1) { // 替换老ast 为新节点
                path.replaceWith(newNodes[0])
            } else {
                path.replaceWithMultiple(newNodes)
            }
        }
    }
}




const sourceCode = `
 class Person {
    constructor(name){
        this.name = name
    }
    getName(){
        return this.name
    }
 }
`

const result = babel.transform(sourceCode, {
    plugins: [transformClasses2]
})


console.log(result.code)